import React, { useRef, useState } from 'react';
import { Link, useModel } from 'umi';

import { ProFormInstance } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';

import * as c from '@/services/consts';
import * as utils from '@/utils/utils';

import * as api from '@/services/order';
import { PageContainer } from '@ant-design/pro-components';
import { Space, Tag } from 'antd';

const OrderList: React.FC = () => {
  const [productId, setProductId] = useState<string | undefined>(undefined);
  const [channelStatList, setChannelStatList] = useState<
    API.OrderChannelStat[] | undefined
  >(undefined);

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();

  const { hasRight } = useModel('useAuthModel');

  const { getProduct, getProductMenuItems } = useModel(
    'useGlobalModel',
    (model) => ({
      getProduct: model.getProduct,
      getProductMenuItems: model.getProductMenuItems,
    }),
  );

  const productMenuItems = getProductMenuItems(true);

  const loadData = async (
    params: { [key: string]: any },
    sorter?: { [key: string]: any },
    filter?: { [key: string]: any },
  ) => {
    const result = await api.list(params, sorter, filter);
    if (result.success) {
      setChannelStatList(result.channelStatList);
    }
    return Promise.resolve(result);
  };

  let columns: ProColumns<API.Order>[] = [
    {
      title: '状态',
      align: 'center',
      width: 80,
      dataIndex: 'orderStatus',
      valueType: 'select',
      sorter: true,
      request: async () => {
        return c.OrderStatusOptions;
      },
    },
    {
      title: '产品',
      align: 'center',
      width: 100,
      dataIndex: 'productId',
      search: false,
      sorter: true,
      renderText: (_, record) => {
        if (record.productId) {
          const product = getProduct(record.productId);
          if (product) {
            return product.name;
          }
        }
        return '';
      },
    },
    {
      title: '会员用户名',
      dataIndex: 'premiumUsername',
      align: 'center',
      sorter: true,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      sorter: true,
    },
    {
      title: '购买方式',
      align: 'center',
      width: 100,
      dataIndex: 'subscribeType',
      search: false,
      sorter: true,
      renderText: (val) => {
        return String(val).toUpperCase();
      },
    },
    {
      title: '支付方式',
      align: 'center',
      width: 100,
      dataIndex: 'payMode',
      search: false,
      sorter: true,
      renderText: (val) => {
        return val ? String(val).toUpperCase() : '';
      },
    },
    {
      title: '渠道',
      dataIndex: 'channel',
      align: 'center',
      search: false,
      sorter: true,
    },
    {
      title: '渠道',
      dataIndex: 'channels',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        mode: 'multiple',
        allowClear: true,
        options: c.PurchaseChannelAllOptions,
      },
    },
    {
      title: '渠道商品',
      dataIndex: 'channelItemId',
      align: 'center',
      // search: false,
      sorter: true,
    },
    {
      title: '渠道订单号',
      dataIndex: 'channelOriginalTradeNo',
      align: 'center',
      sorter: true,
    },
    // {
    //   title: '订单号',
    //   dataIndex: 'orderNo',
    //   align: 'center',
    //   sorter: true,
    // },
    {
      title: '下单时间',
      dataIndex: 'orderTime',
      align: 'center',
      search: false,
      sorter: true,
      renderText: (_, record) => {
        return utils.formatUtcToLocal(record.orderTime);
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      align: 'center',
      search: false,
      sorter: true,
      renderText: (_, record) => {
        return utils.formatUtcToLocal(record.updateTime);
      },
    },
    {
      title: 'IP',
      align: 'center',
      width: 120,
      dataIndex: 'ip',
      sorter: false,
      search: false,
    },
    {
      title: 'IP地区',
      sorter: false,
      search: false,
      render: (_, record) => {
        return (
          <>
            <span>
              {c.getIpArea({
                ip: record.ip,
                ipCountry: record.ipCountry,
                ipProvince: record.ipProvince,
                ipCity: record.ipCity,
                ipNet: record.ipNet,
              })}
            </span>
          </>
        );
      },
    },
    // {
    //   title: '备注',
    //   dataIndex: 'remark',
    //   valueType: 'textarea',
    //   search: false,
    //   ellipsis: true,
    //   sorter: (a, b) => (a.remark ?? '').localeCompare(b.remark ?? ''),
    // },
  ];

  columns = columns.concat([
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 100,
      render: (_, record) => {
        let cmps = [];
        if (hasRight('order_detail')) {
          cmps.push(
            <Link key="info" to={`/buisness/order/detail/${record.id}`}>
              详情
            </Link>,
          );
        }

        return cmps;
      },
    },
  ]);

  return (
    <PageContainer>
      <ProTable<API.Order>
        rowKey="id"
        actionRef={actionRef}
        formRef={formRef}
        search={{
          defaultCollapsed: false,
        }}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        columns={columns}
        toolbar={{
          filter: (
            <>
              <Space
                style={{
                  marginRight: '0px',
                }}
              >
                <span>
                  {channelStatList &&
                    channelStatList.map((c) => {
                      return (
                        <Tag color="blue">
                          <b>
                            {c.channel}: {c.count}
                          </b>
                        </Tag>
                      );
                    })}
                </span>
              </Space>
            </>
          ),
          menu: {
            type: 'tab',
            activeKey: productId,
            items: productMenuItems,
            onChange: (tabKey) => {
              setProductId(tabKey as string);
            },
          },
        }}
        toolBarRender={() => {
          return [];
        }}
        pagination={{
          defaultPageSize: 15,
          pageSizeOptions: ['15', '30', '60', '100'],
          hideOnSinglePage: true,
          // current: pageCurrent,
          // total: totalCount,
        }}
        params={{
          productId:
            productId && productId !== c.DefaultOptionAll.key
              ? parseInt(productId)
              : undefined,
        }}
        request={loadData}
      />
    </PageContainer>
  );
};

export default OrderList;
